package com.lagou.minicat.servlet;

import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;

/**
 * @ClassName Response
 * @Description 响应
 * @Author playboy
 * @Date 2021/5/22 11:58 上午
 * @Version 1.0
 **/
public class Response {

	private OutputStream outputStream;

	public Response(OutputStream outputStream) {
		this.outputStream = outputStream;
	}

	public OutputStream getOutputStream() {
		return outputStream;
	}

	/**
	 * 输出指定的文件到前段
	 *
	 * @param url
	 */
	public void outHtml(String url) throws Exception {
		File file = new File(url);
		if (file.exists() && !file.isDirectory()) {
			//文件存在
			FileInputStream fileInputStream = new FileInputStream(file);
			int available = fileInputStream.available();
			//创建一个缓冲区 1k
			byte[] bytes = new byte[1024];
			//每次读取到的字节数
			int read = 0;

			long count = 0L;

			//如果读到最后，读到的字节数会是-1，以此判断数据流读取完成
			outputStream.write(HttpProtocloUtil.getHeader200(available));
			while ((read = fileInputStream.read(bytes)) != -1) {
				outputStream.write(bytes, 0, read);
				outputStream.flush();
			}
		} else {
			//文件不存在，直接把404提示信息发送给前段
			outputStream.write(HttpProtocloUtil.get404());
		}


	}
}
